package storage.data;

import Common.GlobalConst;


public class MapPage extends Page {
	public static byte pow2 [] = new byte []{1 , 2, 4, 8, 16, 32, 64, -128 } ;
	
	public MapPage ( boolean needData ) {
		super ( needData ) ; 
	}
	
	public MapPage ( Page aPage ) {
		super ( false ) ;
		data = aPage.getData() ; 
	}
	
	public int getPageBit ( PageID pageId ) {
		int pageOffset = pageId.pageId %  ( GlobalConst.PAGESIZE * 8 );
		int byteNumber = pageOffset / 8 ; 
		int byteOffset = pageOffset % 8 ; 
				
		byte tmp = data [ byteNumber ] ;
		int result = ( tmp >> ( 7 - byteOffset )) % 2 == 0 ? 0: 1 ;
		setUsed( true ) ; 
		
		return result ; 
	}

	public void setPageBit ( PageID pageId , int bit ) throws Exception {
		int pageOffset = pageId.pageId %  ( GlobalConst.PAGESIZE * 8 );
		int byteNumber = pageOffset / 8 ; 
		int byteOffset = pageOffset % 8 ; 
				
		byte tmp = data [ byteNumber ] ;
		if ( bit != 0 )  tmp = (byte)((tmp | pow2 [ 7 - byteOffset ]) >> 0) ; // set to 1
		else tmp = (byte)((tmp & (~ pow2 [ 7 - byteOffset ]) ) >> 0) ;
		data [ byteNumber ] = tmp ; 
		setUsed( true ) ;
		setDirty( true ) ; 		
	}
}
